package cn.jdy.plugins.web;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.ScoreRuleUtil;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.IpUtil;
import cn.jdy.payment.service.OrderService;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.plugins.entity.Business;
import cn.jdy.plugins.entity.CollectPK;
import cn.jdy.plugins.entity.Discuss;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.BusinessService;
import cn.jdy.plugins.service.CollectService;
import cn.jdy.plugins.service.DiscussService;
import cn.jdy.plugins.service.IPRecordService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wuzhiliang
 * @title 商机信息控制类
 * @date 2014-03-12
 */
@Controller
@RequestMapping("/business")
public class BusinessCtrl extends BaseCtrl {

  @Autowired
  private BusinessService businessService;
  @Autowired
  private CollectService collectService;
  @Autowired
  private DiscussService discussService;
  @Autowired
  private OrderService orderService;
  @Autowired
  private IPRecordService ipRecordService;


  /**
   * @return /web/business/forSave?businesscode=1&summary=22
   * @title
   * @description: 保存我要加盟信息
   * @author: wangbo
   * @date: 2013-10-15 16:53
   */
  @RequestMapping("/forSave")
  @ResponseBody
  public Map<String, Object> forSave(Business entity) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      Member mbo = super.getMember(false);
      if(null != mbo) {
        entity.setCreater(mbo.getId());
      }
      String date = DateUtil.getCurrentTime();
      entity.setCreateTime(date);
      entity.setUpdateTime(date);
      entity.setStatus("0");
      if(businessService.save(entity) != null) {
        ipRecordService.save(IpUtil.getIp(request), "ipv4", "1");
        if(null != mbo) {
          memberService.updateMoney(mbo.getId(), GlobalConstant.SMONEY_BUSINESS_ADD);
        }
        jsonMap.put("msg", "success");
      } else {
        jsonMap.put("msg", "error");
      }
    } catch(Exception e) {
      jsonMap.put("msg", "error");
      BaseLog.e(this.getClass(), "保存我要加盟信息错误", e);
    }
    return jsonMap;
  }

  /**
   * @return /web/business/forSave?businesscode=1&summary=22
   * @title
   * @description: 保存我要加盟信息
   * @author: wangbo
   * @date: 2013-10-15 16:53
   */
  @RequestMapping("/forSavebusiness")
  public ModelAndView forSavebusiness(Business entity) {
    ModelAndView mv = new ModelAndView("/my/myupsjfile.jsp");
    try {
      Member mbo = (Member) session.getAttribute("user");
      entity.setCreater(mbo.getId());
      String date = DateUtil.getCurrentTime();
      entity.setCreateTime(date);
      entity.setUpdateTime(date);
      entity.setStatus("0");
      if(businessService.save(entity) != null) {
        ipRecordService.save(IpUtil.getIp(request), "ipv4", "1");
        mv.addObject("msg", "success");
      } else {
        mv.addObject("msg", "error");
      }
      mv.addObject("busBo", entity);
      List<ConfValue> businessclassList = confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L);// 商分类 8  放常量
      mv.addObject("classList", businessclassList);
      
      // 预计加盟时间
      Date date1 = new Date();
      mv.addObject("addYear", date1.getYear()+1900);// 当前年份
      mv.addObject("addMonth", date1.getMonth()+1);// 当前月份
    } catch(Exception e) {
      mv.addObject("msg", "error");
      BaseLog.e(this.getClass(), "保存我要加盟信息错误", e);
    }
    return mv;
  }

  /**
   * 商机详细内容页面
   *
   * @param id
   * @return
   */
  @RequestMapping("/detail/{id}")
  public ModelAndView detail(@PathVariable String id) {
    ModelAndView mv = new ModelAndView("/businessDetail.jsp");
    Business business = businessService.queryById(id);
    if(null == business) {
      return new ModelAndView("/404.jsp");
    }
    Member member = super.getMember(false);
    if(member==null) {
      String telephone = business.getTelephone();
      if(telephone!=null && telephone.length()>3) business.setTelephone(telephone.substring(0,3).concat("********"));
    }else if(orderService.queryHasOrder(member.getId(), String.valueOf(business.getId()))) {
      mv.addObject("has", "yes");
    }else {
      String telephone = business.getTelephone();
      if(telephone!=null && telephone.length()>3) business.setTelephone(telephone.substring(0,3).concat("********"));
    }
    if(member != null) {
      CollectPK pk = new CollectPK(member.getId(), business.getId());
      collectService.isBusCollect(pk, business);
    }
    
    mv.addObject("business", business);
    //下载排行榜
    mv.addObject("newbusinesslist", businessService.queryTops("createTime", false));//查询10条最新商机
    mv.addObject("hotbusinesslist", businessService.queryTops("buyTimes", false));//查询10条热门商机
    return mv;
  }

  /**
   * 全站搜索商机信息
   *
   * @return
   */
  @RequestMapping("/search")
  public ModelAndView search(Business entity, Integer pageNo, Integer pageSize, Integer fa, Integer ta, Integer fi,
                             Integer ti, @RequestParam(value = "pinleiId",required = false) Long[] pinleiId) {
    ModelAndView mv = new ModelAndView("/businessList.jsp");
    try {
      if(pageNo==null) pageNo = 1;
      if(pageSize==null) pageSize = 20;

      entity.setiDisplayStart((pageNo - 1) * pageSize);//查询起始值
      entity.setiDisplayLength(pageSize);//查询条数
      entity.setStatus("1");

      Map<String, Object> map = businessService.search(entity, fa, ta, fi, ti, pinleiId);

      List<Business> list = (List<Business>) map.get("dataList");
      //计算用户星级
      for(Business obj : list) {
        Member creater = obj.getMember();
        if(creater!=null) {
          Integer score = creater.getScore();
          if(score==null) score = 0;
          int level = ScoreRuleUtil.getlevel(score);
          level = level > 20 ? 20 : level;
          obj.setCreaterlevel(String.valueOf(level));
        }
      }
      Member member = super.getMember();
      if(member != null) collectService.isCollect(list, member.getId());

      mv.addAllObjects(map);
      mv.addObject("pageNo", pageNo);
      mv.addObject("bClassList", confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));// 查询商机分类信息
      mv.addObject("entity", entity);
      mv.addObject("size", pageSize);
      mv.addObject("fa", fa);
      mv.addObject("ta", ta);
      mv.addObject("fi", fi);
      mv.addObject("ti", ti);
      mv.addObject("pinleiId", pinleiId);
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "全站搜索商机信息错误", e);
    }
    return mv;
  }

  /**
   * 查询商机信息   推荐/最新
   * @return
   */
  @RequestMapping("/queryRecommendOrNewest")
  @ResponseBody
  public Map<String, Object> queryRecommendOrNewest(Business entity, Integer currentPage, Integer pageSize) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      if(currentPage==null) currentPage = 1;
      if(pageSize==null) pageSize = 10;
      entity.setiDisplayStart((currentPage-1) * pageSize);
      entity.setiDisplayLength(pageSize);

      entity.setStatus("1");
      List<Business> list = businessService.query(entity);
      Member member = super.getMember(false);
      if(null != member) {
        list =  collectService.isCollect(list, member.getId());
      }
      //计算用户星级
      for(Business obj : list) {
        Member creater = obj.getMember();
        if(creater!=null) {
          Integer score = creater.getScore();
          if(score==null) score = 0;
          int level = ScoreRuleUtil.getlevel(score);
          level = level > 20 ? 20 : level;
          obj.setCreaterlevel(String.valueOf(level));
          obj.setTelephone("1**********");
        }
      }

      jsonMap.put("dataList", list);
      jsonMap.put("total", businessService.count(entity));
      jsonMap.put("size", pageSize);
      jsonMap.put("currentPage", currentPage);
      jsonMap.put("classId", entity.getClassId());
      jsonMap.put("type", entity.getIsRecommend());
      jsonMap.put("statusCode", 200);
    } catch(Exception e) {
      jsonMap.put("statusCode", 500);
      BaseLog.e(this.getClass(), "查询错误", e);
    }
    return jsonMap;
  }

  /**
   * @return
   * @title
   * @description: 校验加盟手机号是否已经存在
   * @author: wuzhiliang
   * @date: 2014-03-13 16:53
   */
  @RequestMapping("/checkUnickmobile")
  @ResponseBody
  public String checkUnickmobile(String telephone) {
    try {
      Business bo = new Business();
      bo.setTelephone(telephone.trim());
      Long count = businessService.count(bo);
      return count > 0 ? "false" : "true";
    } catch(Exception e) {
      // TODO: handle exception
    }
    return "true";
  }
  /**
   * 校验用户是否有权限上传商机
   */
  @RequestMapping("/authorization")
  @ResponseBody
  public boolean authorization() {
    return ipRecordService.isOperatedToday(IpUtil.getIp(request), "1");
  }

  /**
   * 根据分类查询品类
   */
  @RequestMapping("/queryPinlei")
  @ResponseBody
  public Map<String, Object> queryPinlei(ConfValue bo) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      jsonMap.put("pinleiList", confService.find("pid", bo.getPid()));
      jsonMap.put("statusCode", 200);
    } catch(Exception e) {
      jsonMap.put("statusCode", 500);
      BaseLog.e(getClass(), "查询品类异常！", e);
    }
    return jsonMap;
  }

  /**
   * 查询评论
   * @param discuss
   * @return
   */
  @RequestMapping("/queryDis")
  @ResponseBody
  public Map<String, Object> queryDis(Discuss discuss) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      jsonMap.put("dataList", null);
      jsonMap.put("statusCode", 200);
    } catch(Exception e) {
      jsonMap.put("statusCode", 500);
      BaseLog.e(this.getClass(), "查询评论错误", e);
    }
    return jsonMap;
  }

  /**
   * 提交购买评论
   */
  @RequestMapping("/saveDis")
  @ResponseBody
  public Map<String, Object> saveDis(Discuss entity) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      entity.setUserId(getMember().getId());
      entity.setCreateTime(DateUtil.getCurrentTime());
      discussService.save(entity);
      jsonMap.put("message", "ok");
    } catch(Exception e) {
      jsonMap.put("message", "error");
      BaseLog.e(this.getClass(), "提交购买评论信息错误", e);
    }
    return jsonMap;
  }

}
